package com.itdaan.portal.business.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.itdaan.portal.business.domain.Comment;
import com.itdaan.portal.business.domain.Page;
import com.itdaan.portal.business.domain.WebType;
import com.itdaan.portal.business.mapper.CommentMapper;
import com.itdaan.portal.business.mapper.CommonMapper;
import com.itdaan.portal.business.mapper.WebTypeMapper;
import com.itdaan.portal.business.service.CommentService;
import com.itdaan.portal.common.exception.ServiceException;
/**
 * @author www.itdaan.com
 */
@Service(value = "commentService")
public class CommentServiceImpl implements CommentService {

	@Resource(name = "commentMapper")
	private CommentMapper commentMapper;
	@Resource(name = "webTypeMapper")
	private WebTypeMapper webTypeMapper;
	@Resource(name = "commonMapper") 
	private CommonMapper commonMapper;	
	
	public void insertComment(Comment comment) throws ServiceException {
		//查询当前最大的
		Integer floor = commentMapper.selectMaxFloor(comment);
		comment.setFloor(floor+1);//楼层+1
		commentMapper.insertSelective(comment);//新增评论
	}

	public List<Comment> findCommentByPost(Comment comment)
			throws ServiceException {
		return commentMapper.selectPostComments(comment);
	}

	/**
	 * 审核评论
	 */
	public void updateComment(Comment comment) throws ServiceException {
		Comment oldComment = commentMapper.selectByPrimaryKey(comment.getId());
		int oldAudit = oldComment.getAudit();
		oldComment.setComment(comment.getComment());
		oldComment.setAudit(comment.getAudit());
		oldComment.setAuditUserId(comment.getAuditUserId());
		oldComment.setAuditName(comment.getAuditName());
		oldComment.setAuditContent(comment.getAuditContent());
		commentMapper.updateByPrimaryKeySelective(oldComment);
		//如果之前的评论状态不是审核通过，现在的评论状态是审核通过，则修改该内容的索引状态，重建索引，重建静态页面
		if(oldAudit != Comment.AUDIT_OK && comment.getAudit() == Comment.AUDIT_OK){
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("is_indexed", 0);//重新建立索引
			map.put("is_html_created", 0);//重新创建html
			map.put("html_path", null);//设置html路径为空
			Map<String,Object> data = new HashMap<String, Object>();
			WebType webType = webTypeMapper.selectByPrimaryKey(oldComment.getPostId()/100000000+1);
			String tableName = "t_".concat(webType.getTypeNameEn()).concat("_post_").concat(((oldComment.getPostId()-100000000*(webType.getId()-1))/100000+1)+"");
			data.put("tableName", tableName);
			data.put("map", map);
			data.put("id", oldComment.getPostId());
			commonMapper.updateMap(data);
		}
	}

	public Page findByPage(Page page) throws ServiceException {
		List<Object> comments = commentMapper.getByPage(page);
		int count = commentMapper.getCountByPage(page);
		page.setDatas(comments);
		page.setCount(count);
		return page;
	}

	
	
}
